package com.liuxinlong.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liuxinlong.common.AosException;
import com.liuxinlong.constant.SystemConstants;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.ParameterDao;
import com.liuxinlong.modules.entity.SystemParameter;
import com.liuxinlong.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 物料成本卷积服务器service
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2023年05月25日
 * 2024.08.13 修改GET请求为POST
 */
@Service
@Slf4j
public class ConvolutionService implements ConvolutionInterface {

    private final static String MATERIAL_CONVOLUTION_URL = "http://172.30.109.57:8868/Service.asmx/Get_xx_json";

    @Autowired
    private ParameterDao parameterDao;

    @Override
    public Map<String,Object> checkMaterial(String materialNo, String region) {
        StringBuffer buffer = new StringBuffer();
        SystemParameter sp = parameterDao.getParameterByName(SystemConstants.ROLLUP_SERVER_IP);
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
//        String targetUrl = sp.getValue() + "?cuserId=pt_chk&cprograme=xxrollupcost.p&cparams=" + materialNo + "^" + region + "^";
        String targetUrl = sp.getValue();
        Map<String,Object> result = new HashMap<>();
        try {
            URL url = new URL(targetUrl);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

//            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

//            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
//            httpUrlConn.setRequestProperty("Connection", "keep-alive");
//            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
//            httpUrlConn.setRequestProperty("Content-Length", "0");
//            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
//            httpUrlConn.setRequestProperty("charset", "UTF-8");

            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            Map<String, Object> param = new HashMap<>();
            param.put("cuserid", "pt_chk");
            param.put("programname", "xxrollupcost.p");
            param.put("cparams", materialNo + "^" + region + "^");
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            System.out.println(buffer);
            log.info("buffer",buffer);
//            int i = buffer.indexOf("{");
//            String resuStr = buffer.substring(i);
            JSONObject res = JSONUtil.parseObj(buffer);
            JSONObject data = (JSONObject) res.get("Data");
            JSONObject item = (JSONObject) data.get("Item");
            result.put("return_qnum",item.get("return_qnum"));
            result.put("return_result",item.get("return_result"));
            result.put("return_ref",item.get("return_ref"));
            System.out.println(res);
            log.info("res",res);
            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "物料验证失败");
        }
        return result;
    }

    @Override
    public Map<String,Object> rollingMaterialPrice(String id,String materialNo, String region) {
        StringBuffer buffer = new StringBuffer();
        SystemParameter sp = parameterDao.getParameterByName(SystemConstants.ROLLUP_SERVER_IP);
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        String targetUrl = sp.getValue();
//        String targetUrl = sp.getValue() + "?cuserId=cost_mt&cprograme=xxrollupcost.p&cparams="+ id + "^" + materialNo + "^" + region + "^";
        Map<String,Object> result = new HashMap<>();
        try {
            URL url = new URL(targetUrl);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
//            httpUrlConn.setConnectTimeout(5000);
//            httpUrlConn.setReadTimeout(5000);
//            httpUrlConn.setDoOutput(true);
//            httpUrlConn.setDoInput(true);

//            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

//            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            Map<String, Object> param = new HashMap<>();
            param.put("cuserid", "cost_mt");
            param.put("programname", "xxrollupcost.p");
            param.put("cparams", id + "^" + materialNo + "^" + region + "^");
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
//            int i = buffer.indexOf("{");
//            String resuStr = buffer.substring(i);
//            JSONObject res = JSONUtil.parseObj(resuStr);
            JSONObject res = JSONUtil.parseObj(buffer);
            JSONObject data = (JSONObject) res.get("Data");
            JSONObject item = (JSONObject) data.get("Item");
            result.put("return_qnum",item.get("return_qnum"));
            result.put("return_result",item.get("return_result"));
            result.put("return_ref",item.get("return_ref"));
            System.out.println(res);
            log.info("res",res);
            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "物料滚价失败");
        }
        return result;
    }

    @Override
    public Map<String, Object> changeMaterialStatus(String id, String materialNo, String region, String targetStatus) {
        StringBuffer buffer = new StringBuffer();
        SystemParameter sp = parameterDao.getParameterByName(SystemConstants.ROLLUP_SERVER_IP);
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        String targetUrl = sp.getValue();
//        String targetUrl = sp.getValue() + "?cuserId=status_mt&cprograme=xxrollupcost.p&cparams="+ id + "^" + materialNo + "^" + region + "^" + targetStatus + "^";
        Map<String,Object> result = new HashMap<>();
        try {
            URL url = new URL(targetUrl);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
//            httpUrlConn.setConnectTimeout(5000);
//            httpUrlConn.setReadTimeout(5000);
//            httpUrlConn.setDoOutput(true);
//            httpUrlConn.setDoInput(true);
//
//            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            Map<String, Object> param = new HashMap<>();
            param.put("cuserid", "status_mt");
            param.put("programname", "xxrollupcost.p");
            param.put("cparams", id + "^" + materialNo + "^" + region + "^" + targetStatus + "^");
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
//            int i = buffer.indexOf("{");
//            String resuStr = buffer.substring(i);
//            JSONObject res = JSONUtil.parseObj(resuStr);
//            result.put("return_qnum",res.get("return_qnum"));
//            result.put("return_result",res.get("return_result"));
//            result.put("return_ref",res.get("return_ref"));
            JSONObject res = JSONUtil.parseObj(buffer);
            JSONObject data = (JSONObject) res.get("Data");
            JSONObject item = (JSONObject) data.get("Item");
            result.put("return_qnum",item.get("return_qnum"));
            result.put("return_result",item.get("return_result"));
            result.put("return_ref",item.get("return_ref"));
            System.out.println(res);
            log.info("res",res);
            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "物料状态修改失败");
        }
        return result;
    }

    @Override
    public Map<String,Object> getMaterialStatus(String materialNo, String region) {
        StringBuffer buffer = new StringBuffer();
        SystemParameter sp = parameterDao.getParameterByName(SystemConstants.ROLLUP_SERVER_IP);
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        String targetUrl = sp.getValue();
//        String targetUrl = sp.getValue() + "?cuserId=status_gt&cprograme=xxrollupcost.p&cparams=" + materialNo + "^" + region + "^";
        Map<String,Object> result = new HashMap<>();
        try {
            URL url = new URL(targetUrl);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
//            httpUrlConn.setConnectTimeout(5000);
//            httpUrlConn.setReadTimeout(5000);
//            httpUrlConn.setDoOutput(true);
//            httpUrlConn.setDoInput(true);
//
//            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");


            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            Map<String, Object> param = new HashMap<>();
            param.put("cuserid", "status_gt");
            param.put("programname", "xxrollupcost.p");
            param.put("cparams",  materialNo + "^" + region + "^");
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            System.out.println(buffer);
            log.info("buffer",buffer);
//            int i = buffer.indexOf("{");
//            String resuStr = buffer.substring(i);
//            JSONObject res = JSONUtil.parseObj(resuStr);
//            result.put("return_qnum",res.get("return_qnum"));
//            result.put("return_result",res.get("return_result"));
//            result.put("return_ref",res.get("return_ref"));
            JSONObject res = JSONUtil.parseObj(buffer);
            JSONObject data = (JSONObject) res.get("Data");
            JSONObject item = (JSONObject) data.get("Item");
            result.put("return_qnum",item.get("return_qnum"));
            result.put("return_result",item.get("return_result"));
            result.put("return_ref",item.get("return_ref"));
            System.out.println(res);
            log.info("res",res);
            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "物料验证失败");
        }
        return result;
    }
}
